﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Data.Common;

/// <summary>
/// Allows an application, bundles and languages to be selected.
/// </summary>
public partial class ApplicationSelector : System.Web.UI.UserControl
{
    private Database db;

    /// <summary>
    /// Gets the ID of the selected application.
    /// </summary>
    /// <value>The selected application ID.</value>
    public string SelectedApplicationID {
        get { return radApplication.SelectedValue; }
    }

    /// <summary>
    /// Gets the applications visible in the application RadioButtonList.
    /// Text = DisplayName, Value = ID
    /// </summary>
    /// <value>The applications.</value>
    public ListItemCollection Applications {
        get {
            return radApplication.Items;
        }
    }

    /// <summary>
    /// Gets the IDs of the selected bundles.
    /// </summary>
    /// <value>The selected bundles.</value>
    public List<string> SelectedBundles {
        get {
            List<string> bundles = new List<string>();
            foreach(ListItem itm in lstBundles.Items) {
                if(itm.Selected) {
                    bundles.Add(itm.Value);
                }
            }
            return bundles;
        }
    }

    /// <summary>
    /// Gets the CultureInfo.Names selected languages.
    /// </summary>
    /// <value>The selected languages.</value>
    public List<string> SelectedLanguages {
        get {
            List<string> languages = new List<string>();
            foreach(ListItem itm in lstLanguages.Items) {
                if(itm.Selected) {
                    languages.Add(itm.Value);
                }
            }
            return languages;
        }
    }

    /// <summary>
    /// Gets the CultureInfo.Names and English names of the selected languages.
    /// </summary>
    /// <value>The selected languages.</value>
    public Dictionary<string, string> SelectedLanguagesWithKeys {
        get {
            Dictionary<string, string> languages = new Dictionary<string, string>();
            foreach(ListItem itm in lstLanguages.Items) {
                if(itm.Selected) {
                    languages.Add(itm.Text, itm.Value);
                }
            }
            return languages;
        }
    }

    /// <summary>
    /// Loads the available applications and selects the first item.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Init(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            radApplication.DataBind();
            if(radApplication.Items.Count > 0) {
                radApplication.SelectedIndex = 0;
                ShowLanguages(null, EventArgs.Empty);
            }
        }
    }

    /// <summary>
    /// Registers a script to remove the 'Refresh' button when JavaScript is enabled.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
        ScriptManager.RegisterStartupScript(this, typeof(Page), "nojs", "$('#" + btnRefresh.ClientID + "').remove();", true);
    }


    /// <summary>
    /// Shows the languages and bundles for the application selected.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ShowLanguages(object sender, EventArgs e) {
        if(radApplication.SelectedValue == null) {
            return;
        }
        if(db == null || !db.Connected) {
            db = new Database();
            db.OpenConnection();
        }
        //todo: re-factor this...
        using(Database.Command cmd = db.CreateCommand()) {
            cmd.CommandText = "SELECT languages FROM " + db.TablePrefix + "applications WHERE id = @p";
            cmd.AddParameterWithValue("@p", radApplication.SelectedValue);
            ListComparer cmp = new ListComparer();
            List<ListItem> tempLanguages = new List<ListItem>(),
                           tempBundles = new List<ListItem>();
            lstLanguages.Items.Clear();
            string rawLanguages = cmd.ExecuteScalar().ToString();
            foreach(string abbrev in rawLanguages.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) {
                ListItem itm = new ListItem(Utils.GetSafeEnglishName(abbrev), abbrev);
                itm.Selected = true;
                tempLanguages.Add(itm);
            }
            tempLanguages.Sort(cmp);
            lstLanguages.Items.AddRange(tempLanguages.ToArray());
            if(lstLanguages.Items.Count == 0) {
                ListItem itm = new ListItem(Resources.UIStrings.NoLanguagesFound, "");
                itm.Selected = true;
                lstLanguages.Items.Add(itm);
                lstLanguages.Enabled = false;
            } else {
                lstLanguages.Enabled = true;
            }

            lstBundles.Items.Clear();
            cmd.CommandText = "SELECT id, name FROM " + db.TablePrefix + "bundles WHERE application = @p";
            DbDataReader reader = cmd.ExecuteReader();
            while(reader.Read()) {
                ListItem itm = new ListItem(reader["name"].ToString(), reader["id"].ToString());
                itm.Selected = true;
                tempBundles.Add(itm);
            }
            tempBundles.Sort(cmp);
            lstBundles.Items.AddRange(tempBundles.ToArray());
            if(lstBundles.Items.Count == 0) {
                ListItem itm = new ListItem(Resources.UIStrings.NoBundlesFound, "");
                itm.Selected = true;
                lstBundles.Items.Add(itm);
                lstBundles.Enabled = false;
            } else {
                lstBundles.Enabled = true;
            }
            reader.Close();
        }
        db.CloseConnection();
    }
}
